package com.gasolinator.a.app.db;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import com.gasolinator.a.util.AssetsUtil;

import java.io.IOException;

public class DatabaseHelper extends SQLiteOpenHelper {
	 
    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.gasolinator.a/databases/";
    private static String DB_NAME = "gaswalker.db";
 
    private SQLiteDatabase myDataBase;
 
    private final Context myContext;
 
    /**
     * Constructor
     * Takes and keeps a reference of the passed contextdd in order to access to the application assets and resources.
     * @param context
     */
    public DatabaseHelper(Context context) {
    	super(context, DB_NAME, null, 1);
        this.myContext = context;
    }	
 
    /**
     * Creates a empty database on the system and rewrites it with your own database.
     */
    public void createDataBase() throws IOException {
     	boolean dbExist = checkDataBase();
 
    	if (dbExist) {
    		//do nothing - database already exist
    	} else {
    		SQLiteDatabase db = null;
        	try {
        		db = this.getReadableDatabase();
     			copyDataBase();
     		} catch (IOException e) {
         		throw new Error("Error copying database");
         	} finally {
         		db.close();
         	}
    	}
     }

    private void copyDataBase() throws IOException {
        AssetsUtil.createDatabaseFile(this.myContext);
    }

    private boolean checkDataBase() {
    	SQLiteDatabase checkDB = null;

    	try {
    		String myPath = DB_PATH + DB_NAME;
    		checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
     	} catch (SQLiteException e) {
     		//database does't exist yet.
     	}

    	if (checkDB != null) {
     		checkDB.close();
     	}

    	return checkDB != null ? true : false;
    }

    public SQLiteDatabase openDataBase() throws SQLException {
     	//Open the database
        String myPath = DB_PATH + DB_NAME;
    	myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    	return myDataBase;
     }
 
    @Override
	public synchronized void close() {
    	if (myDataBase != null) myDataBase.close();
   	    super.close();
 	}
 
	@Override
	public void onCreate(SQLiteDatabase db) {
 
	}
 
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
	}
}